<template>
  <div class="edit-container">
    <!-- 1.顶部栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <!-- 2.头部 -->
    <div class="avatar">
      <van-image width="120" height="120" round fit="cover" :src="userInfo.photo" />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 3.编辑操作 -->
    <van-cell-group>
      <van-cell title="名称" :value="userInfo.name" is-link @click="editNameClick" />
      <van-cell title="性别" :value="userInfo.gender?'女':'男'" is-link @click="showPopup = true" />
      <van-cell
        title="生日"
        :value="userInfo.birthday"
        is-link
        @click="showDatePick = true;currentDate=new Date(userInfo.birthday)"
      />
    </van-cell-group>

    <!-- 编辑姓名弹窗 -->
    <van-dialog v-model="showDialog" title="编辑姓名" show-cancel-button @confirm="updateName">
      <van-field ref="input" v-model="newName" placeholder="请输入姓名" />
    </van-dialog>

    <!-- 编辑性别弹窗 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-nav-bar title="修改性别" left-arrow @click-left="showPopup = false" />
      <van-cell title="男" is-link @click="updateGender(0)" />
      <van-cell title="女" is-link @click="updateGender(1)" />
    </van-popup>

    <!-- 编辑生日弹窗 -->
    <van-popup v-model="showDatePick" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showDatePick=false"
        @confirm="updateBirthday"
      />
    </van-popup>

    <!-- 图片裁切 -->
    <div class="cropper" v-show="showCropper">
      <vueCropper ref="cropper" :img="img" autoCrop autoCropWidth="120" autoCropHeight="120"></vueCropper>
      <van-button type="primary" @click="showCropper=false">取消</van-button>
      <van-button type="info" @click="updatePhoto">确认</van-button>
    </div>
  </div>
</template>

<script>
// 导入mapState辅助函数
import { mapState } from "vuex";
// 导入接口
import { editUserInfo, editUserPhoto } from "./user.js";
import * as moment from "moment";

// 导入vue-cropper
import { VueCropper } from "vue-cropper";

export default {
  name: "edit",
  components: {
    VueCropper
  },
  data() {
    return {
      showDialog: false, //编辑姓名弹窗
      newName: "", //姓名输入框
      showPopup: false, //编辑性别弹窗
      showDatePick: false, //编辑生日弹窗
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      img: "", //要裁切的图片
      showCropper: false //裁切盒子显示/隐藏
    };
  },
  methods: {
    // 1. 点击修改名字按钮
    editNameClick() {
      // (1)弹出dialog弹窗
      this.showDialog = true;
      // (2)输入框默认要是当前用户名字
      this.newName = this.userInfo.name;
      // (3)输入框默认成为焦点 原生DOM.focus
      // 问题：输入框无法聚焦
      // 原因：vuex渲染dom操作是一个异步过程。不会走到这里就立即渲染，而是要等这个方法走完过一会才会渲染dom。直接在这个方法中是无法操作dom的
      // setTimeout(() => {this.$refs.input.focus()}, 100); 时间不好控制
      //
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    updateName() {
      // 2.1 调用接口
      editUserInfo({ name: this.newName }).then(res => {
        console.log(res);
        // 2.2 弹窗提示
        this.$toast.success("更新成功");
        // 2.3 更新vuex
        this.$store.commit("updateUserInfo", {
          ...this.userInfo,
          name: this.newName
        });
      });
    },
    // 3.修改性别
    updateGender(gender) {
      // 3.1 调用接口
      editUserInfo({ gender }).then(res => {
        // (1)弹出提示
        this.$toast.success("更新成功");
        // (2)隐藏popup
        this.showPopup = false;
        // (3)更新vuex
        this.$store.commit("updateUserInfo", {
          ...this.userInfo,
          gender
        });
      });
    },
    // 4.编辑生日
    updateBirthday() {
      // (1)转换日期格式
      let birthday = moment(this.currentDate).format("YYYY-MM-DD");
      console.log(birthday);
      // (2)发请求
      editUserInfo({ birthday }).then(res => {
        console.log(res);
        // 隐藏弹窗
        this.showDatePick = false;
        // 弹出提示
        this.$toast.success("更新成功");
        // (3)更新vuex
        this.$store.commit("updateUserInfo", {
          ...this.userInfo,
          birthday
        });
      });
    },
    // 5.选择文件
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
      // console.log(file.content);  //base64
      console.log(file.file); //文件对象（原生DOM获取的就是这个）
      console.log(URL.createObjectURL(file.file)); //blob

      // 1.设置裁切图片的路径(cropper组件不支持file对象，但是支持base64)
      this.img = file.content;
      // 2.显示裁切盒子
      this.showCropper = true;
    },
    // 6.上传裁切后的图片
    updatePhoto() {
      // 1.获取裁切之后的图片(组件默认CV的时候就加了ref="cropper")
      this.$refs.cropper.getCropBlob(async data => {
        // 2.上传服务器
        // (1)生成formData对象
        let fd = new FormData();
        fd.append("photo", data);
        // (2).提交文件到服务器
        let res = await editUserPhoto(fd);

        this.$toast.success("更新成功");
        this.showCropper = false;
        this.$store.commit("updateUserInfo", {
          ...this.userInfo,
          photo: res.data.data.photo
        });
        // editUserPhoto(fd).then(res => {
        //   console.log(res);
        //   // (2.1)弹窗提示
        //   this.$toast.success("更新成功");
        //   // (2.2)隐藏裁切框
        //   this.showCropper = false
        //   // (2.3)更新vuex
        //   this.$store.commit("updateUserInfo", {
        //     ...this.userInfo,
        //     photo: res.data.data.photo
        //   });
        // });
      });
    }
  },
  computed: {
    // 添加计算属性  userInfo = return this.$store.state.userInfo
    ...mapState(["userInfo"])
  }
};
</script>

<style lang="less">
.edit-container {
  .van-nav-bar__content {
    background-color: #009afb;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-nav-bar__text {
      color: #fff;
    }
  }

  .avatar {
    display: flex;
    height: 150px;
    justify-content: center;
    align-items: center;
    .van-uploader {
      position: absolute;
      opacity: 0;
      width: 120px;
      height: 120px;
      .van-uploader__upload {
        width: 120px;
        height: 120px;
      }
    }
  }

  // 裁切盒子
  .cropper {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    .van-button--primary {
      position: absolute;
      left: 0;
      bottom: 0;
    }
    .van-button--info {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>
